<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link
      rel="stylesheet"
      href="/js/layui/css/layui.css"
      th:href="@{/js/layui/css/layui.css}"
    />
    <link
      rel="stylesheet"
      href="/css/device.css"
      th:href="@{/css/device.css}"
    />
  </head>

  <body>
    <div style="display: flex">
      <div class="layui-row layui-col-space15">
        <div class="layui-col-md6">
          <div class="layui-panel">
            <div id="Tree1"></div>
          </div>
        </div>
      </div>
      <div class="center">
        <!-- 设备管理 -->
        <div class="container">
          <div class="rightCard">
            <div class="top layui-panel">
              <button
                type="button"
                class="layui-btn layui-btn-normal createBtn"
              >
                创建设备管理
              </button>
              <div class="search">
                <input
                  type="text"
                  required
                  lay-verify="required"
                  placeholder="请输入预警名称"
                  autocomplete="off"
                  class="layui-input searchInput"
                />
                <i class="layui-icon layui-icon-search"></i>
              </div>
            </div>
            <!-- 右卡片搜索位置 end -->

            <!-- 表格部分 start -->
            <div class="layui-panel">
              <table id="table" lay-filter="test"></table>
              <div id="pages"></div>
            </div>
            <!-- 表格部分 end -->
          </div>
        </div>

        <!-- 创建工单弹窗 start -->
        <div id="popupDiv" style="display: none">
          <label class="layui-form-label required">名称</label>
          <div class="layui-input-block">
            <input
              type="text"
              name="title"
              required
              lay-verify="required"
              placeholder="请输入名称"
              autocomplete="off"
              class="layui-input warningNames"
            />
          </div>
          <label class="layui-form-label required">预警ID</label>
          <div class="layui-input-block">
            <input
              type="text"
              name="title"
              lay-verify="required"
              placeholder="请输入预警ID"
              autocomplete="off"
              class="layui-input warningCodes"
            />
          </div>
          <form class="layui-form" action="">
            <div class="layui-form-item">
              <label class="layui-form-label">预警类型</label>
              <div class="layui-input-block">
                <select name="warningSelect" lay-verify="required">
                  <option value="">请选择</option>
                  <option value="0">同比</option>
                  <option value="1">环比</option>
                </select>
              </div>
            </div>
          </form>
          <div class="layui-tab" lay-filter="filter">
            <!-- <ul class="layui-tab-title">
            <li lay-id="0" data-index="0" class="layui-this">同比</li>
            <li lay-id="1" data-index="1">环比</li>
          </ul> -->
            <div class="layui-tab-content">
              <div class="layui-tab-item layui-show">
                <div class="historySelect">
                  <div class="layui-form-item history">
                    <label class="layui-form-history required">历史场景</label>
                    <div class="inp">
                      <div class="selectSpan form-control">请选择历史场景</div>
                      <div id="selectData" style="display: none"></div>
                    </div>
                  </div>
                  <div class="layui-inline dateSelect">
                    <label class="layui-form-label required">开始时间</label>
                    <input
                      type="text"
                      class="layui-input startTimes"
                      id="test1"
                      lay-verify="required"
                      placeholder="选择开始时间"
                      autocomplete="off"
                    />
                    <label class="layui-form-label required">结束时间</label>
                    <input
                      type="text"
                      class="layui-input endTimes"
                      id="test2"
                      lay-verify="required"
                      placeholder="选择结束时间"
                      autocomplete="off"
                    />
                  </div>
                </div>
              </div>
              <!-- <div class="layui-tab-item">
              <div class="historySelect">
                <div class="layui-form-item history">
                  <div class="inp">
                    <div class="selectSpans form-control">请选择历史场景</div>
                    <div id="selectDatas" style="display: none"></div>
                  </div>
                </div>
                <div class="layui-inline dateSelect">
                  <label class="layui-form-label">开始时间</label>
                  <input
                    type="text"
                    class="layui-input startTimes"
                    id="test1"
                    lay-verify="required"
                    placeholder="选择开始时间"
                    autocomplete="off"
                  />
                  <label class="layui-form-label">结束时间</label>
                  <input
                    type="text"
                    class="layui-input endTimes"
                    id="test2"
                    lay-verify="required"
                    placeholder="选择结束时间"
                    autocomplete="off"
                  />
                </div>
              </div>
            </div> -->
            </div>
          </div>
          <div class="bottomBtn">
            <button class="layui-btn layui-btn-sm addbtn">确定</button>
            <button class="layui-btn layui-btn-sm layui-btn-primary cancelBtn">
              取消
            </button>
          </div>
        </div>
        <!-- 创建工单弹窗 end -->
      </div>
    </div>

    <!-- 编辑按钮弹窗 start -->
    <div id="setBtnPopup" style="display: none">
      <form
        class="layui-form setBtnForm"
        id="addGoodsForm"
        onsubmit="return false"
      >
        <div>
          <label class="layui-form-label required">场景编号</label>
          <div class="layui-input-block">
            <input
              name="sceneId"
              readonly
              type="text"
              required
              lay-verify="required"
              placeholder="请输入场景编号"
              autocomplete="off"
              class="layui-input warningName"
            />
          </div>
        </div>
        <div>
          <label class="layui-form-label required">预警ID</label>
          <div class="layui-input-block">
            <input
              name="warningCode"
              type="text"
              lay-verify="required"
              placeholder="请输入id"
              autocomplete="off"
              class="layui-input warningName"
            />
          </div>
        </div>
        <div>
          <label class="layui-form-label required">预警名称</label>
          <div class="layui-input-block">
            <input
              name="warningName"
              type="text"
              lay-verify="required"
              placeholder="请输入标题"
              autocomplete="off"
              class="layui-input warningName"
            />
          </div>
        </div>

        <div class="layui-form-item">
          <label class="layui-form-label">预警类型</label>
          <div class="layui-input-block">
            <select name="warningType" id="sel" lay-verify="required">
              <option value=""></option>
              <option value="0">同比预警</option>
              <option value="1">环比预警</option>
            </select>
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">启用状态</label>
          <div class="layui-input-block">
            <select name="status" lay-verify="required">
              <option value=""></option>
              <option value="0">启用</option>
              <option value="1">禁用</option>
            </select>
          </div>
        </div>
        <div class="layui-form-item">
          <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="formDemo">
              立即提交
            </button>
            <button class="layui-btn layui-btn-primary setBtn">取消</button>
          </div>
        </div>
      </form>
    </div>
    <!-- 编辑按钮弹窗 end -->

    <script src="/js/jquery.min.js" th:src="@{/js/jquery.min.js}"></script>
    <script src="/js/layui/layui.js" th:src="@{/js/layui/layui.js}"></script>
    <script th:inline="javascript">
      // 表格部分
      $(function () {
        // 左侧树形
        layui.use(["tree"], function () {
          var treeCkData = { id: 0 };
          var tree = layui.tree;
          $.ajax({
            method: "get",
            url: "/youtian/workspace-category/workspaceCategoryTree",
            success: function (res) {
              console.log("左侧工作区数据=============", res.data);
              if (res.code == 0) {
                var inst1 = tree.render({
                  elem: "#Tree1", //绑定元素
                  data: res.data,
                  id: "leftTree",
                  click: function (obj) {
                    $.ajax({
                      method: "get",
                      url: "/youtian/workspace-category/getPointList",
                      data: {
                        workspaceCategoryId: obj.data.id,
                        pageSize: 300000,
                      },
                      success: function (res) {
                        tableList(res);
                        console.log(res, "res");
                      },
                    });
                    treeData = obj.data;
                    if (obj.data.id !== treeCkData.id) {
                      // 点击左侧工作树高亮显示
                      $('div[data-id="' + obj.data.id + '"] span')
                        .eq(1)
                        .last()
                        .addClass("clickColor");
                      $('div[data-id="' + treeCkData.id + '"] span')
                        .eq(1)
                        .last()
                        .removeClass("clickColor");
                      treeCkData = obj.data;
                    }
                    console.log(
                      $('div[data-id="' + treeCkData.id + '"] span'),
                      "spa======n"
                    );
                    $(".setDataName").val(obj.data.title);
                    console.log(
                      $(".setDataid").val(obj.data.id),
                      "===================id"
                    );
                    console.log(obj.data, treeData.title); // 得到当前点击的节点数据 上级区域标题
                    console.log(obj.state); // 得到当前节点的展开状态：open、close、normal
                    console.log(obj.elem[0], "obj.elem[0]"); // 得到当前节点元素
                    console.log(obj.data.children); //当前节点下是否有子节点
                  },
                });
              } else {
                layer.msg("数据请求失败，请稍后重试");
              }
            },
          });
          //渲染
        });

        // 预警设置列表请求
        var earlyWarningData = {};
        layui.use(["table", "element", "layer", "dropdown"], function () {
          var table = layui.table;
          var layer = layui.layer;
          var data = {
            pageSize: 300,
          }
          /**
           * 顶部搜索按钮
           *
           */
          $(".layui-icon-search").on("click", function () {
            let warningName = $(".searchInput").val();
            $.ajax({
              method: "post",
              url: "/earlyWarning/list1",
              data: { warningName },
              success: function (res) {
                console.log(res, "筛选成功");
                tableFn(res.rows);
              },
            });
          });
          /**
           *
           * 表格渲染数据
           */
          function earlyWarningList() {
            $.ajax({
              method: "post",
              url: "/earlyWarning/list1",
              data: {
                pageSize: 300000,
              },
              success: function (res) {
                console.log(res, "res");
                if (res.code == 0) {
                  tableFn(res.rows);
                  // let div = $(".layui-table-body table tbody").find(
                  //   "[data-field=warningType] .layui-table-cell"
                  // );
                  // console.log(div, "div");
                  // for (let i = 0; i < div.length; i++) {
                  //   let divVal = div[i].innerText;
                  //   console.log(divVal);
                  //   if (divVal == 0) {
                  //     div[i].innerText = "同比预警";
                  //     console.log("同比yujing");
                  //   } else {
                  //     div[i].innerText = "环比预警";
                  //     console.log("环比预警");
                  //   }
                  // }
                } else {
                  layui.layer.msg("获取数据失败", { icon: 2 });
                }
              },
            });
          }
          /**
           *  表格实例
           * */
          function tableFn(rows) {
            table.render({
              elem: "#table",
              id: "idTest",
              height: 450,
              page: true, //开启分页
              data: rows,
              cols: [
                [
                  //表头
                  {
                    field: "id",
                    title: "序号",
                    width: "5.6%",
                    align: "center",
                    type: "numbers",
                  },
                  {
                    field: "warningCode",
                    title: "预警编号",
                    width: "10%",
                    align: "center",
                  },
                  {
                    field: "sceneName",
                    title: "场景名称",
                    width: "10%",
                    align: "center",
                  },
                  {
                    field: "warningName",
                    title: "预警名称",
                    width: "15%",
                    align: "center",
                  },
                  {
                    field: "startTime",
                    title: "创建时间",
                    width: "15%",
                    align: "center",
                  },
                  {
                    field: "createBy",
                    title: "创建人",
                    width: "10%",
                    align: "center",
                  },
                  {
                    field: "warningType",
                    title: "预警方式",
                    width: "10%",
                    align: "center",
                    templet: $("#pageBox"),
                  },
                  {
                    field: "status",
                    title: "启用状态",
                    width: "10%",
                    align: "center",
                    templet: $("#stateCheckbox"),
                  },
                  {
                    field: "words",
                    title: "操作",
                    width: "15%",
                    templet: "#toolEventDemo",
                    align: "center",
                  },
                ],
              ],
            });
          }
          earlyWarningList();
          var tableObj = {};
          console.log("test");
          /**
           * 分页功能
           * */
          var laypage = layui.laypage;
          laypage.render({
            elem: "pages", //注意，这里的 test1 是 ID，不用加 # 号
            count: 50, //数据总数，从服务端得到
            limit: 2,  // 每页条数
            limits: [2,4,6],  // 每页条数的选择项
            layout: ['count', 'prev', 'page', 'next', 'limit']
          });
          /**
           *  表格开关按钮
           * */
          layui.form.on("switch(statusBtn)", function (data) {
            let datas = {};
            datas.ids = data.value;
            console.log(datas.ids, data.elem.checked, "datas.ids");
            if (data.elem.checked) {
              datas.status = "0";
            } else {
              datas.status = "1";
            }
            $.ajax({
              method: "post",
              url: "/earlyWarning/changeEarlyWaringStatus",
              data: datas,
              success: function (res) {
                console.log(res, "btnres");
                if (res.code == 0) {
                  if (data.elem.checked) {
                    layui.layer.msg("开启状态");
                  } else {
                    layui.layer.msg("关闭状态");
                  }
                  earlyWarningList();
                } else {
                  layui.layer.msg("请求失败", { icon: 2 });
                }
              },
            });
          });
          //单元格工具事件
          table.on("tool(test)", function (obj) {
            // 注：test 是 table 原始标签的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）
            if (layEvent === "del") {
              console.log(obj, "obj");
              //删除
              layer.confirm("确定删除吗？", function (index) {
                $.ajax({
                  method: "post",
                  url: `/earlyWarning/remove?ids=${obj.data.id}`,
                  success: function (res) {
                    if (res.code == 0) {
                      layui.layer.msg("删除成功", { icon: 1 });
                    } else {
                      layui.layer.msg("删除失败，请稍后重试", { icon: 2 });
                    }
                  },
                });
                console.log(data, "data");
                console.log(obj.data.id, "obj.data.id");
                obj.del(); // 删除对应行（tr）的 DOM 结构，并更新缓存
                layer.close(index);
                earlyWarningList();
                // 向服务端发送删除请求，执行完毕后，可通过 reloadData 方法完成数据重载
              });
            } else if (layEvent === "edit") {
              //编辑
              console.log(obj.data, obj, "obj.data");
              $("[name=sceneId]").val(obj.data.sceneId);
              $("[name=warningCode]").val(obj.data.warningCode);
              $("[name=warningName]").val(obj.data.warningName);
              $("[name=warningType]").val(obj.data.warningType);
              $("[name=status]").val(obj.data.status);
              layui.form.render("select");
              var indexs = layer.open({
                type: 1,
                title: "编辑",
                area: ["700px", "500px"],
                move: false,
                content: $("#setBtnPopup"), //这里content是一个普通的String
                cancel: function (index, layero) {
                  $("#popupDiv").css("display", "none");
                  layer.close(indexs);
                },
              });
              //提交
              layui.form.on("submit(formDemo)", function (data) {
                data.field.id = obj.data.id;
                console.log(data.field, "field");
                $.ajax({
                  method: "post",
                  url: "/earlyWarning/edit",
                  data: data.field,
                  success: function (res) {
                    if (res.code == 0) {
                      layui.layer.msg("修改成功", { icon: 1 });
                      let currpage = $(".layui-laypage-em").next().text();
                      earlyWarningList();
                    } else {
                      layui.layer.msg("修改失败，请稍后再试", { icon: 1 });
                    }
                  },
                });
                console.log(13323);
                layer.close(indexs);
              });
              $(".setBtn").on("click", function () {
                layer.close(indexs);
              });
            }
          });

          /**
           *
           * 点击创建预警后弹窗
           *
           * */
          var index;
          $(".createBtn").on("click", function () {
            layui.use(["layer", "laydate", "form"], function () {
              var layer = layui.layer;
              index = layer.open({
                type: 1,
                title: "预警创建",
                area: ["700px", "500px"],
                move: false,
                content: $("#popupDiv"), //这里content是一个普通的String
                cancel: function (index, layero) {
                  $("#popupDiv").css("display", "none");
                  layer.close(index);
                  $("#selectData").fadeOut();
                  $(".selectSpan").html("请选择历史场景");
                },
              });
              /**
               * 点击取消关闭弹窗
               */
              $(".cancelBtn").on("click", function () {
                layui.layer.close(index);
                $(".startTimes").val("");
                $(".endTimes").val("");
                $(".selectSpan").html("请选择历史场景");
                $(".warningNames").val("");
                $(".warningCodes").val("");
                $("#selectData").fadeOut();
              });

              /**
               * 点击下拉框选择左侧树数据
               */
              var tree = layui.tree;

              $(".selectSpan").on("click", function () {
                $("#selectData").fadeIn();
                $.ajax({
                  method: "get",
                  url: "/youtian/scene-category/tree",
                  success: function (res) {
                    var tree = layui.tree;
                    var inst1 = tree.render({
                      elem: "#selectData",
                      data: res.data,
                      click: function (obj) {
                        $("#selectData").fadeOut();
                        $(".selectSpan").html(obj.data.title);
                        console.log("obj.data.title=======", obj.data.title);
                        earlyWarningData.sceneId = obj.data.id;
                      },
                    });
                  },
                });
              });

              /**
               * 弹窗里的日期
               * */
              // 执行一个laydate实例
              layui.laydate.render({
                elem: "#test1", //指定元素
                done: function (value, date, endDate) {
                  earlyWarningData.startTime = value;
                  console.log(value); //得到日期生成的值，如：2017-08-18
                  console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
                  console.log(endDate); //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。
                },
              });
              layui.laydate.render({
                elem: "#test2", //指定元素
                done: function (value, date, endDate) {
                  earlyWarningData.endTime = value;
                  console.log(value); //得到日期生成的值，如：2017-08-18
                  console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
                  console.log(endDate); //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。
                },
              });
              /**
               * tab栏切换事件
               */
              // layui.use("element", function () {
              //   var element = layui.element;
              //   element.init("tab", "filter");
              //   element.on("tab(filter)", function (data) {
              //     console.log(data, 'tabdata');
              //     earlyWarningData.warningType = data.index;
              //     $(".selectSpan").html("请选择历史场景");
              //     $(".startTimes").val("");
              //     $(".endTimes").val("");
              //   });
              // });

              /**
               * 点击确定后请求
               */
            });
          });
          $(".addbtn").on("click", function (event) {
            earlyWarningData.warningName = $(".warningNames").val();
            earlyWarningData.warningCode = $(".warningCodes").val();
            earlyWarningData.warningType = $("[name=warningSelect]").val();
            console.log(earlyWarningData, "earlyWarningData");

            let warningName = layui.form.validate(".warningNames");
            let warningCode = layui.form.validate(".warningCodes");
            let startTime = layui.form.validate(".startTimes");
            let endTime = layui.form.validate(".endTimes");
            let selectSpan = $(".selectSpan").html();
            console.log(warningName, warningCode, startTime, endTime, "验证");
            if (warningName && warningCode && startTime && endTime) {
              if (selectSpan == "请选择历史场景") {
                layer.msg("必填项不能为空", { icon: 5, anim: 6 });
              } else {
                $.ajax({
                  method: "post",
                  url: "/earlyWarning/add",
                  data: earlyWarningData,
                  success: function (res) {
                    console.log(res, "res");
                    if (res.code == 0) {
                      layui.layer.msg("新增成功", { icon: 1 });
                      earlyWarningList();
                    } else {
                      layui.layer.msg("新增失败,请稍后再试", { icon: 2 });
                    }
                    $(".startTimes").val("");
                    $(".endTimes").val("");
                    $(".selectSpan").html("请选择历史场景");
                    $(".warningNames").val("");
                    $(".warningCodes").val("");
                    $("[name=warningSelect]").val("");
                    layui.layer.close(index);
                  },
                });
              }
            }
          });
        });
      });
    </script>

    <script type="text/html" id="stateCheckbox">
      <input type="checkbox" name="status" value="{{d.id}}"
      lay-filter="statusBtn" lay-skin="switch" {{d.status == '0' ? 'checked' :
      ''}} />
    </script>
    <script type="text/html" id="pageBox">
      {{# if(d.warningType == 0){ }} 同比预警 {{# } }} {{# if(d.warningType ==
      1){ }} 环比预警 {{# } }}
    </script>
    <script type="text/html" id="toolEventDemo">
      <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
      <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"
        >删除</a
      >
    </script>
  </body>
</html>
